package cn.yunhe.controller;

import cn.yunhe.model.Role;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * Created by zs on 2017/12/6.
 */
@Controller
@RequestMapping("/attr")
@SessionAttributes(names = {"id"}, types = {Role.class})
public class AttributeController {

    /**
     * \
     * 控制器获取request请求中的id值
     *
     * @param id
     * @return
     */
    @RequestMapping("/requestAttribute")
    public ModelAndView reqAttr(@RequestAttribute("id") Long id) {
        System.out.println("id===" + id);
        ModelAndView mv = new ModelAndView();
        Role role = new Role();
        role.setId(2L);
        role.setRoleName("广东省");
        role.setNote("广广广");

        mv.addObject("role", role);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    /**
     * 将数据存到Session中,传递到前台
     *
     * @param id
     * @return
     */
    @RequestMapping("/sessionAttributes")
    public ModelAndView sessionAttrs(Long id) {
        ModelAndView mv = new ModelAndView();
        Role role = new Role();
        role.setId(5L);
        role.setRoleName("聂明宇");
        role.setNote("龙腾");

        //根据类型，session会保存角色信息
        mv.addObject("role", role);
        //根据类型，session会保存id
        mv.addObject("id", id);
        mv.setViewName("sessionAttribute");
        return mv;
    }

    /**
     * 接收前台session的传值
     *
     * @param id
     * @return
     */
    @RequestMapping("/sessionAttribute")
    public ModelAndView sessionAttr(@SessionAttribute("id") Long id) {
        ModelAndView mv = new ModelAndView();
        System.out.println("id====" + id);
        mv.addObject("id", id);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }


    /**
     * 从Cookie和HTTP获取对应的请求信息
     *
     * @param userAgent
     * @param jsessionId
     * @return
     */
    @RequestMapping("/getHeaderAndCookie")
    public String testHeaderAndCookie(
            @RequestHeader(value = "User-Agent", required = false, defaultValue = "attribute") String userAgent,
            @CookieValue(value = "JSESSIONID", required = true, defaultValue = "MyJsessionId") String jsessionId) {
        System.out.println("user-agent=" + userAgent);
        System.out.println("jsessionid=" + jsessionId);
        return "index";
    }


}
